233. 数字 1 的个数
为保证权益,题目请参考 233. 数字 1 的个数(From LeetCode).
解决方案1
Python
python
# 233. 数字 1 的个数
# https://leetcode-cn.com/problems/number-of-digit-one/
class Solution:
def countDigitOne(self, n: int) -> int:
beforeLevelNumber = [0, 1]
for i in range(10):
t = beforeLevelNumber[-1]
t = 10 ** (i + 1) + 10 * t
beforeLevelNumber.append(t)
# print(beforeLevelNumber)
count = 0
beforeAllNumber = 0
for i, num in enumerate(reversed(list(str(n)))):
# print(i)
if num >= "2":
count += int(num) * beforeLevelNumber[i]
count += 10 ** i
elif num == "1":
count += beforeAllNumber + 1
count += beforeLevelNumber[i]
else:
pass
beforeAllNumber = beforeAllNumber + int(num) * (10 ** i)
return count
if __name__ == "__main__":
solution = Solution()
print(solution.countDigitOne(20))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33